package org.springframework.samples.countries.web.translate;

import java.io.InputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.Type;

import pikes.samples.countries.ui.peak.BehaviourPage;

public class ASMTranslator implements Translator {

	protected static final Log translatorLogger = LogFactory.getLog("Translator");

	private boolean translateEmptyBodyAsReturn = false;

	public boolean isTranslateEmptyBodyAsReturn() {
		return translateEmptyBodyAsReturn;
	}

	public void setTranslateEmptyBodyAsReturn(boolean translateEmptyBodyAsReturn) {
		this.translateEmptyBodyAsReturn = translateEmptyBodyAsReturn;
	}

	public Behaviour translate(Class<? extends BehaviourPage> clazz) throws TranslationFailedException {
		try {
			Behaviour behaviour = new Behaviour();
			String newName = Type.getInternalName(clazz) + ".class";
			translatorLogger.info("Translating: " + newName);
			InputStream is = this.getClass().getClassLoader().getResourceAsStream(newName);
			if (is == null) {
				throw new NullPointerException();
			}
			ClassReader cr = new ClassReader(is);
			cr.accept(new PageMemberFunctionTranslator(behaviour, translateEmptyBodyAsReturn), false);
			return behaviour;
		}
		catch (Exception e) {
			translatorLogger.warn("Can't translate class", e);
			throw new TranslationFailedException(e);
		}
	}

}
